﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using GlxRRSDB.ReportDataSetTableAdapters;
using GlxRRSDB;
using GlxRRSMain.Utils;

namespace GlxRRSMain.UserControls
{
    public partial class ImportFilmRevenueDataControl : UserControl
    {
        private class ImportFilm
        {
            public int filmId = 0;
            public string filmTitle;
            public DateTime startDate = DateTime.MinValue;
            public DateTime endDate = DateTime.MinValue;
        }
        private tblFilmTableAdapter x_tblFilmTableAdapter = new tblFilmTableAdapter();
        private tblFilmRevenueTableAdapter x_tblFilmRevenueTableAdapter = new tblFilmRevenueTableAdapter();
        private System.Data.DataSet DtSet;
        private Dictionary<string, ImportFilm> dictFilmTitleById = new Dictionary<string, ImportFilm>();
        //
        public ImportFilmRevenueDataControl()
        {
            InitializeComponent();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            DataTable dtTable = DtSet.Tables[0];
            #region get all film in datagrid
            DateTime cachedDateTime = DateTime.MinValue;
            for (int i = 1; i < dtTable.Rows.Count; i++)
            {
                string filmTitle = dtTable.Rows[i][4].ToString();
                if (filmTitle == null || filmTitle.Length < 1) continue;
                string strDate = dtTable.Rows[i][3].ToString();
                if (strDate != null && !"".Equals(strDate) && filmTitle != null && filmTitle.Length > 1)
                {
                    cachedDateTime = DateTime.Parse(strDate);
                }
                //
                if (dictFilmTitleById.ContainsKey(filmTitle))
                {
                    ImportFilm film = dictFilmTitleById[filmTitle];
                    if (cachedDateTime > film.endDate)
                        film.endDate = new DateTime(cachedDateTime.Ticks);
                }
                else
                {
                    ImportFilm film = new ImportFilm();
                    film.filmTitle = filmTitle;
                    film.startDate = new DateTime(cachedDateTime.Ticks);
                    film.endDate = new DateTime(cachedDateTime.Ticks);
                    dictFilmTitleById.Add(filmTitle, film);
                }
            }
            #endregion
            #region import film data
            foreach (ImportFilm film in dictFilmTitleById.Values)
            {
                if (x_tblFilmTableAdapter.GetData().Where(f => f.FilmTitle == film.filmTitle).ToList().Count == 0)
                {
                    // insert new film
                    int id = x_tblFilmTableAdapter.Insert(film.filmTitle, film.startDate, film.endDate, "A");
                    if (id > 0)
                    {
                        ReportDataSet.tblFilmRow a1 = x_tblFilmTableAdapter.GetData()
                                                   .Where(f => f.FilmTitle == film.filmTitle)
                                                   .First();
                        film.filmId = a1.ID;
                    }
                    continue;
                }
                // insert or update
                ReportDataSet.tblFilmRow existFilm = x_tblFilmTableAdapter.GetData()
                                               .Where(f => f.FilmTitle == film.filmTitle)
                                               .First();
                if (existFilm == null)
                {
                    // insert new film
                    int id = x_tblFilmTableAdapter.Insert(film.filmTitle, film.startDate, film.endDate, "A");
                    if (id > 0)
                    {
                        ReportDataSet.tblFilmRow a1 = x_tblFilmTableAdapter.GetData()
                                                   .Where(f => f.FilmTitle == film.filmTitle)
                                                   .First();
                        film.filmId = a1.ID;
                    }
                }
                else
                {
                    film.filmId = existFilm.ID;
                    // update time
                    // check start date
                    if (existFilm.StartDate == DateTime.MinValue || existFilm.StartDate > film.startDate)
                    {
                        existFilm.StartDate = film.startDate;
                    }
                    else
                    {
                        film.startDate = existFilm.StartDate;
                    }
                    // check end date
                    if (existFilm.FinishDate == DateTime.MinValue || existFilm.FinishDate > film.endDate)
                    {
                        existFilm.FinishDate = film.endDate;
                    }
                    else
                    {
                        film.endDate = existFilm.FinishDate;
                    }
                    // update
                    x_tblFilmTableAdapter.Update(existFilm);
                }
            }
            #endregion
            #region import film revenue
            int cachedCinemaID = 0;
            //
            for (int i = 0; i < dtTable.Rows.Count; i++)
            {
                string cinemaName = dtTable.Rows[i][0].ToString();
                if (cinemaName.ToLower().Contains("total"))
                {
                    continue;
                }
                if (cinemaName.ToLower().Contains("nguyen du"))
                {
                    cachedCinemaID = 1001;
                }
                else if (cinemaName.ToLower().Contains("nguyen trai"))
                {
                    cachedCinemaID = 1002;
                }
                else if (cinemaName.ToLower().Contains("tan binh"))
                {
                    cachedCinemaID = 1003;
                }
                //
                string strDate = dtTable.Rows[i][3].ToString();
                if (strDate.ToLower().Contains("total"))
                {
                    continue;
                }
                if (strDate.ToLower().Length > 7)
                {
                    cachedDateTime = DateTime.Parse(strDate); ;
                }
                string filmTitle = dtTable.Rows[i][4].ToString();

                if (!dictFilmTitleById.ContainsKey(filmTitle))
                {
                    continue;
                }
                ImportFilm film = dictFilmTitleById[filmTitle];
                int admits = int.Parse(dtTable.Rows[i][5].ToString());
                float bo = float.Parse(dtTable.Rows[i][6].ToString());
                //
                x_tblFilmRevenueTableAdapter.Insert(cachedCinemaID, film.filmId, admits, (int) bo, cachedDateTime);
            }
            #endregion
            MessageBox.Show("Imported total:" + dtTable.Rows.Count + " rows");
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            importFileDialog.Filter = "Excel (.xlsx)|*.xlsx|All Files (*.*)|*.*";
            importFileDialog.FilterIndex = 1;
            importFileDialog.Multiselect = false;

            // Call the ShowDialog method to show the dialog box.
            DialogResult userClickedOK = importFileDialog.ShowDialog();

            // Process input if the user clicked OK.
            if (userClickedOK == DialogResult.OK)
            {
                // Open the selected file to read.
                textBox1.Text = importFileDialog.FileName;
                loadDataGrid(textBox1.Text);
            }

        }
        private void loadDataGrid(string path)
        {
            try
            {
                DtSet = FileHelper.getDataSetFromExcel(path);
                dataGridView1.DataSource = DtSet.Tables[0];
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
